<template>
  <div class="OutlierQuery">
    <div class="filter">
      <el-form ref="form" label-width="90px">
        <div class="operation">
          <el-form-item label="识别状态:">
            <!-- <el-checkbox-group v-model="queryForm.resultStatus">
              <el-checkbox :label="0" name="type">识别正常</el-checkbox>
              <el-checkbox :label="1" name="type">识别异常</el-checkbox>
            </el-checkbox-group>-->
            <el-radio-group v-model="queryForm.reconStatus">
              <el-radio :label="0">识别正常</el-radio>
              <el-radio :label="1">识别异常</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开始时间:">
            <el-date-picker
              v-model="queryForm.startTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期时间"
              :picker-options="startPickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间:">
            <el-date-picker
              v-model="queryForm.endTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期时间"
              :picker-options="endPickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-button class="but-query" type="text" size="medium" @click="queryClick">
            <i class="query-icon"></i>查询
          </el-button>
          <el-button class="but-reset" type="text" size="medium" @click="resetClick">
            <i class="reset-icon"></i>重置
          </el-button>
          <el-button class="but-export" type="text" size="medium" @click="exportClick">
            <i class="export-icon"></i>导出
          </el-button>
        </div>
      </el-form>
    </div>
    <div class="content">
      <div class="content-left">
        <div class="left-head">设备树</div>
        <div class="tree-list">
          <Tree-List
            ref="TreeList"
            :data="allDeviceTreeList"
            :showIcon="true"
            :showState="true"
            @vtl_dataChange="treeDataChange"
            :activedDisabled="true"
          ></Tree-List>
        </div>
      </div>
      <div class="content-right">
        <div class="right-head">用户操作</div>
        <div class="content-list">
          <el-table
            ref="outlierTableData"
            :data="tableData"
            border
            stripe
            size="mini"
            class="el-table-redefine"
            style="width: 100%;"
            height="100%"
            @selection-change="handleSelectionChange"
            @row-click="onRowClick"
          >
            <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
            <el-table-column type="selection" align="center" width="50"></el-table-column>
            <el-table-column prop="reconType.name" label="识别类型">
              <template slot-scope="scope">
                <span>{{scope.row.reconType.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="point.name" label="点位名称">
              <template slot-scope="scope">
                <span>{{scope.row.point.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="识别结果">
              <template slot-scope="scope">
                <span>{{scope.row ? matchArrayContentStr(scope.row.value, meterReadingDealWith) : "未知"}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="modifyValue" label="审核结果">
              <template slot-scope="scope">
                <span>{{scope.row.modifyValue}}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="alarmLevel" label="告警等级"></el-table-column> -->
            <el-table-column prop="createTime" label="识别时间"></el-table-column>
            <el-table-column prop="saveType.id" label="采集信息">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  class="picture-button"
                  @click.stop="showImage(scope.row.flirPic)"
                  v-if="scope.row.point && (scope.row.point.saveTypeId === 1 || scope.row.point.saveTypeId === 4)"
                >红外图片</el-button>
                <el-button
                  type="text"
                  size="mini"
                  class="picture-button"
                  @click.stop="showImage(scope.row.cameraPic)"
                  v-if="scope.row.point && (scope.row.point.saveTypeId === 2 || scope.row.point.saveTypeId === 4)"
                >可见光图片</el-button>
                <!-- 3 音频 -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-area">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper, slot"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[20, 50, 100, 300]"
            :page-size="queryForm.size"
            :current-page="queryForm.page"
            :total="alarmTotal"
          >
            <el-button type="text" size="mini">前往</el-button>
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  dateToDateStr,
  getDateTopMonth,
  dateToDateWithToSecondStr
} from "@/utils/utilsMethod";
import { pointsTree, pointHistoryList } from "@/api/apiManagement";
import Viewer from "viewerjs";
import "viewerjs/dist/viewer.css";
import { formatJson } from "@/utils";
import { matchArrayContent, MeterReadingDealWith } from "@/utils/constant";
import TreeList from "@/components/TreeList";

export default {
  components: { TreeList },
  data() {
    return {
      robot_id: null,
      //
      substationName: "",
      //
      multipleSelection: [],
      //
      allDeviceTreeList: [],
      topCheckTreeId: "",

      queryForm: {
        page: 1,
        size: 20,
        robotId: null,
        // taskHistoryId: null,
        pointIds: "",
        startTime: "",
        endTime: "",
        // saveType: null,
        // checkStatus: null,
        reconStatus: 0
      },
      alarmTotal: 0,
      tableData: [],
      pointsList: [],
      startPickerOptions: {
        disabledDate: time => {
          let endTime =
            this.queryForm.endTime === null ? "" : this.queryForm.endTime;
          return (
            time.getTime() > new Date(endTime).getTime() ||
            time.getTime() > Date.now() - 8.64e6
          );
        }
      },
      endPickerOptions: {
        disabledDate: time => {
          let startTime =
            this.queryForm.startTime === null ? "" : this.queryForm.startTime;
          return (
            time.getTime() <
              new Date(startTime).getTime() - 8 * 60 * 60 * 1000 ||
            time.getTime() > Date.now() - 8.64e6
          ); //如果没有后面的-8.64e6就是不可以选择今天的   减去一天的时间代表可以选择同一天
        }
      },
      meterReadingDealWith: MeterReadingDealWith
    };
  },
  created() {
    this.robot_id = localStorage.getItem("ydRobot_id");
    //
    this.queryForm.startTime = dateToDateStr(getDateTopMonth(new Date()));
    this.queryForm.endTime = dateToDateStr(new Date());
    this.queryForm.robotId = this.robot_id;
    //
    this.getPointsTree();
  },
  mounted() {},
  methods: {
    /**
     * 该方法用于将有父子关系的数组转换成树形结构的数组
     * 接收一个具有父子关系的数组作为参数
     * 返回一个树形结构的数组
     */
    translateArrayToTree(data) {
      let tempData = data;
      //没有父节点的数据
      let parent = data.filter(item => {
        if (item.parentId == "undefined" || item.parentId == null) {
          return true;
        } else {
          if (tempData.some(it => it.id === item.parentId)) {
            return false;
          } else {
            return true;
          }
        }
      });
      //有父节点的数据
      let children = data.filter(item => {
        if (item.parentId !== "undefined" && item.parentId != null) {
          if (tempData.some(it => it.id === item.parentId)) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      });
      //定义转换方法的具体实现
      let translator = (parent, children) => {
        //遍历父节点数据
        parent.forEach(parentItem => {
          //遍历子节点数据
          children.forEach((childrenItem, index) => {
            //此时找到父节点对应的一个子节点
            if (parentItem.id === childrenItem.parentId) {
              //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
              let temp = JSON.parse(JSON.stringify(children));
              //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
              temp.splice(index, 1);
              //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
              translator([childrenItem], temp);
              //把找到子节点放入父节点的children属性中
              typeof parentItem.children !== "undefined" &&
              parentItem.children !== null
                ? parentItem.children.push(childrenItem)
                : (parentItem.children = [childrenItem]);
            }
          });
        });
      };
      //调用转换方法
      translator(parent, children);
      //返回最终的结果
      return parent;
    },
    //
    filterTree() {
      this.$refs.TreeList.vtl_setCurrentNodeId({});
    },
    // 点位树
    getPointsTree() {
      pointsTree()
        .then(response => {
          if (response) {
            this.allDeviceTreeList = response;
            this.filterTree();
          }
        })
        .catch(() => {});
    },
    // 判断传入的节点是不是选中节点的子节点
    checkBelongToChooseNode(value, data, node) {
      const level = node.level;
      // 如果传入的节点本身就是一级节点就不用校验了
      if (level === 1) {
        return false;
      }
      // 先取当前节点的父节点
      let parentData = node.parent;
      // 遍历当前节点的父节点
      let index = 0;
      while (index < level - 1) {
        // 如果匹配到直接返回
        // if (parentData.data.name.indexOf(value) !== -1) {
        //   return true;
        // }
        var bRet = false;
        var arr = value.split(" ");
        for (var i = 0, len = arr.length; i < len; i++) {
          if (parentData.data.name.indexOf(arr[i]) !== -1) {
            bRet = true;
          }
        }
        if (bRet) {
          return true;
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent;
        index++;
      }
      // 没匹配到返回false
      return false;
    },
    getAlarmLevelClassName(value) {
      if (value === 0) {
        return "normal";
      }
      if (value === 1) {
        return "warning";
      }
      if (value === 2) {
        return "general-alarm";
      }
      if (value === 3) {
        return "serious-alarm";
      }
      if (value === 4) {
        return "danger-alarm";
      }
    },
    getPointHistoryList(param) {
      param.startTime = param.startTime == null ? "" : param.startTime;
      param.endTime =
        param.endTime == null
          ? ""
          : param.endTime.length <= 10 && param.endTime.length != 0
          ? param.endTime + " 24:00:00"
          : param.endTime;
      pointHistoryList(param)
        .then(response => {
          this.alarmTotal = response.total;
          if (response && response.list) {
            this.tableData = response.list;
          }
        })
        .catch(() => {});
    },
    //
    queryClick() {
      // this.queryForm.pointIds
      var checkTree = this.$refs.TreeList.vtl_getCurrentNode();
      if (checkTree && checkTree.leaf == true) {
        if (
          typeof checkTree.id === "string" &&
          checkTree.id.indexOf("point_") != -1
        ) {
          let index = checkTree.id.lastIndexOf("_");
          let slice = checkTree.id.substring(index + 1);
          this.queryForm.pointIds = slice;
        }
      } else {
        let pointIdsArr = [];
        var tempList = this.$refs.TreeList.vtl_getLeafNodesId();
        if (checkTree) {
          tempList = this.$refs.TreeList.vtl_getParentNodeLeafNodesId(
            checkTree
          );
        }
        pointIdsArr = tempList.map(item => {
          if (typeof item === "string" && item.indexOf("point_") != -1) {
            let index = item.lastIndexOf("_");
            let slice = item.substring(index + 1);
            return slice;
          }
          return "";
        });
        this.queryForm.pointIds = pointIdsArr.join(",");
      }
      if (this.topCheckTreeId != this.queryForm.pointIds) {
        this.queryForm.page = 0;
        this.queryForm.size = 20;
        this.tableData = [];
      }
      this.topCheckTreeId = this.queryForm.pointIds;

      this.getPointHistoryList(this.queryForm);
    },
    resetClick() {
      this.queryForm.page = 1;
      this.queryForm.size = 20;
      this.queryForm.reconStatus = 0;
      this.queryForm.pointIds = "";
      this.queryForm.startTime = dateToDateStr(getDateTopMonth(new Date()));
      this.queryForm.endTime = dateToDateStr(new Date());
      //
      this.getPointsTree();
    },
    exportClick() {
      if (this.multipleSelection.length > 0) {
        require.ensure([], () => {
          const { export_json_to_excel } = require("vendor/Export2Excel");
          const tHeader = [
            "识别类型",
            "点位名称",
            "识别结果",
            "审核结果",
            "识别时间",
            "采集信息"
          ];
          const filterVal = [
            "reconType.name",
            "point.name",
            "value",
            "modifyValue",
            "createTime",
            "picUrl"
          ];
          let temp = JSON.parse(JSON.stringify(this.multipleSelection));
          const data = formatJson(filterVal, this.formatAlartType(temp));
          export_json_to_excel(
            tHeader,
            data,
            "识别异常点查询表" + dateToDateWithToSecondStr(new Date())
          );
        });
      } else {
        this.$message({
          message: "请选择数据"
        });
      }
    },
    formatAlartType(data) {
      let array = data.slice(0);
      array.forEach((item, index) => {
        var picUrl =
          item.point &&
          (item.point.saveTypeId === 1 || item.point.saveTypeId === 4)
            ? item.flirPic
            : item.point.saveTypeId === 2
            ? item.cameraPic
            : "";
        var picType =
          item.point &&
          (item.point.saveTypeId === 1 || item.point.saveTypeId === 4)
            ? "红外图片"
            : item.point.saveTypeId === 2
            ? "可见光图片"
            : "";
        item["picUrl"] = picType + "_" + picUrl;
        item["value"] = matchArrayContent(item["value"], MeterReadingDealWith);
      });
      return array;
    },
    showImage(val) {
      var image = new Image();
      image.src = val;
      var viewer = new Viewer(image, {
        navbar: false,
        hidden: function() {
          viewer.destroy();
        }
      });
      viewer.show();
    },

    handleSizeChange(val) {
      this.queryForm.size = val;
      this.getPointHistoryList(this.queryForm);
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      this.getPointHistoryList(this.queryForm);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    onRowClick(row, column, event) {
      this.$refs.outlierTableData.toggleRowSelection(row);
    },
    treeDataChange(tree, list, obj) {
      this.queryForm.pointIds = this.getAllPointIds();
      this.getPointHistoryList(this.queryForm);
    },
    getAllPointIds() {
      var temp = this.$refs.TreeList.vtl_getLeafNodesId().map(item => {
        if (typeof item === "string" && item.indexOf("point_") != -1) {
          let index = item.lastIndexOf("_");
          let slice = item.substring(index + 1);
          return slice;
        }
        return "";
      });
      return temp.join(",");
    },
    // 匹配类型返回
    matchArrayContentStr(val, array) {
      return matchArrayContent(val, array);
    }
  }
};
</script>

<style>
.OutlierQuery .filter .el-form-item {
  margin-top: 0;
  margin-bottom: 3px;
}
.OutlierQuery .filter .el-form-item__label {
  font-size: 13px;
  line-height: 26px;
}
.OutlierQuery .filter .el-form-item__content {
  font-size: 13px;
  line-height: 26px;
}
.OutlierQuery .filter .el-radio__label {
  font-size: 13px;
}
.OutlierQuery .filter .el-checkbox {
  font-size: 13px;
  margin-right: 10px;
}
.OutlierQuery .filter .el-checkbox__label {
  font-size: 13px;
}
.OutlierQuery .filter .el-radio {
  width: 86px;
  margin-left: 10px;
}
.OutlierQuery .filter .el-radio + .el-radio {
  margin-left: 5px;
}
.OutlierQuery .filter .el-checkbox {
  width: 90px;
  margin-left: 5px;
}
.OutlierQuery .filter .el-checkbox + .el-checkbox {
  margin-left: 10px;
}
.OutlierQuery .content-left .custom-tree-node span {
  font-size: 13px;
}
/*  */

.OutlierQuery {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}
.OutlierQuery .filter {
  position: relative;
  width: 100%;
  /* height: 65px; */
  background-color: #eeeeee;
}
.OutlierQuery .operation {
  width: 100%;
  height: 30px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
  border-top: 1px solid rgb(202, 231, 238);
}

.OutlierQuery .operation .el-form-item {
  margin-top: 1px;
  margin-bottom: 0;
  float: left;
}
.OutlierQuery .operation .el-form-item__content {
  width: 230px;
  margin-left: 5px !important;
}
.OutlierQuery .operation .el-form-item__content {
  /* width: 200px; */
  margin-left: 5px !important;
  line-height: 26px;
  float: left;
}
.OutlierQuery .operation .el-date-editor.el-input {
  width: 200px;
}
.OutlierQuery .operation .el-input__inner {
  height: 26px;
  line-height: 26px;
}
.OutlierQuery .operation .el-input__icon {
  line-height: 26px;
}
.OutlierQuery .but-query,
.OutlierQuery .but-reset,
.OutlierQuery .but-export {
  height: 30px;
  margin-left: 10px;
  margin-right: 20px;
  padding: 0;
  font-size: 13px;
  color: #000;
  float: left;
}
.OutlierQuery .query-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/query.png);
  background-size: 100% 100%;
  float: left;
}
.OutlierQuery .reset-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/reset_a.png);
  background-size: 100% 100%;
  float: left;
}
.OutlierQuery .export-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/export.png);
  background-size: 100% 100%;
  float: left;
}

.OutlierQuery .content {
  width: 100%;
  flex-grow: 1;
}
.OutlierQuery .content-left {
  position: relative;
  width: 300px;
  height: 100%;
  /* background-color: #eeeeee; */
  background-color: #fff;
  border-right: 1px solid rgb(202, 231, 238);
  float: left;
}
.OutlierQuery .content-right {
  position: relative;
  /* width: 100%; */
  width: calc(100% - 300px);
  height: 100%;
  /* margin-left: 300px; */
  /* padding: 0 0 0 10px; */
  border-left: 1px solid rgb(202, 231, 238);
  float: left;
}
.OutlierQuery .left-head {
  width: 100%;
  height: 27px;
  padding: 0 5px;
  line-height: 27px;
  font-size: 13px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}
.OutlierQuery .tree-list {
  position: absolute;
  width: 100%;
  height: calc(100% - 27px);
  /* overflow: auto; */
}
.OutlierQuery .right-head {
  width: 100%;
  height: 27px;
  padding: 0 5px;
  line-height: 27px;
  font-size: 13px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}

.OutlierQuery .content-list {
  position: absolute;
  width: 100%;
  height: calc(100% - 59px);
  /* overflow: auto; */
}

.OutlierQuery .pagination-area {
  position: absolute;
  width: 100%;
  height: 32px;
  bottom: 0px;
  background-color: #eeeeee;
}

.OutlierQuery .el-table-redefine {
  width: 100%;
  height: 100%;
  /* display: flex;
  flex-flow: column; */
}

.OutlierQuery .el-table-redefine .el-table__body-wrapper {
  /* overflow: hidden;
  overflow-y: auto;
  flex-grow: 1; */
}

.OutlierQuery .folder {
  width: 13px;
  height: 13px;
  margin-top: 2px;
  /* background-color: rgb(10, 158, 80); */
  background-image: url(../../../static/resources/images/folder.png);
  background-size: 100% 100%;
  float: left;
}
.OutlierQuery .file {
  width: 13px;
  height: 13px;
  margin-top: 2px;
  /* background-color: rgb(255, 0, 0); */
  background-image: url(../../../static/resources/images/file.png);
  background-size: 100% 100%;
  float: left;
}

.OutlierQuery .alarm {
  width: 12px;
  height: 13px;
  margin: 3px 2px 0 2px;
  float: left;
}
.OutlierQuery .normal {
  background-color: rgb(50, 150, 50);
}
.OutlierQuery .warning {
  background-color: rgb(0, 0, 255);
}
.OutlierQuery .general-alarm {
  background-color: rgb(255, 255, 0);
}
.OutlierQuery .serious-alarm {
  background-color: rgb(255, 128, 10);
}
.OutlierQuery .danger-alarm {
  background-color: rgb(155, 0, 0);
}
</style>